package xyz.moxj.sp11.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import xyz.moxj.sp01.util.JsonResult;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //前置,后置,路由,过滤类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    //排序顺序
    @Override
    public int filterOrder() {
        return 6;
    }
    //是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");

        //如果没有token
        if (StringUtils.isBlank(token)) {
            //阻止继续访问
            ctx.setSendZuulResponse(true);
            //直接返回响应
            ctx.addZuulResponseHeader("Content-Type","application/json");
            ctx.setResponseStatusCode(JsonResult.NOT_LOGIN);
            ctx.setResponseBody(JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("not login").toString()
            );
        }
        return null;
    }
}
